{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**230. Kth Smallest Element in a BST**  <font color=#f0ad4e size=3>_medium_</font>\n",
    "\n",
    "Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.\n",
    "\n",
    "**Node:**\n",
    "You may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n",
    "\n",
    "**Example 1**\n",
    "\n",
    "```\n",
    "Input: root = [3,1,4,null,2], k = 1\n",
    "   3\n",
    "  / \\\n",
    " 1   4\n",
    "  \\\n",
    "   2\n",
    "Output: 1\n",
    "```\n",
    "\n",
    "**Example 2**\n",
    "\n",
    "```\n",
    "Input: root = [5,3,6,2,4,null,null,1], k = 3\n",
    "       5\n",
    "      / \\\n",
    "     3   6\n",
    "    / \\\n",
    "   2   4\n",
    "  /\n",
    " 1\n",
    "Output: 3\n",
    "```\n",
    "**Follow up:**\n",
    "What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "# def in_order_traverse(root, k=1, ordered=[]):\n",
    "#     if root is None or len(ordered) == k: return\n",
    "#     if root.left is not None:\n",
    "#         in_order_traverse(root.left, k, ordered)\n",
    "#     ordered.append(root.val)\n",
    "#     if root.right is not None:\n",
    "#         in_order_traverse(root.right, k, ordered)\n",
    "\n",
    "def kthSmallest(root, k):\n",
    "    \"\"\"\n",
    "    :type root: TreeNode\n",
    "    :type k: int\n",
    "    :rtype: int\n",
    "    \"\"\"\n",
    "    # ordered = []\n",
    "    # in_order_traverse(root, k, ordered)\n",
    "    # return ordered[k - 1]\n",
    "\n",
    "    ordered = []\n",
    "    stack = []\n",
    "    while root:\n",
    "        while root:\n",
    "            stack.append(root)\n",
    "            root = root.left\n",
    "\n",
    "        root = stack.pop()\n",
    "        ordered.append(root.val)\n",
    "        if len(ordered) == k: return ordered[k-1]\n",
    "\n",
    "        while root.right is None:\n",
    "            root = stack.pop()\n",
    "            ordered.append(root.val)\n",
    "            if len(ordered) == k: return ordered[k - 1]\n",
    "\n",
    "        if root.right:\n",
    "            root = root.right\n",
    "\n",
    "class TreeNode:\n",
    "    def __init__(self, x):\n",
    "        self.val = x\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    node_1 = TreeNode(1)\n",
    "    node_2 = TreeNode(2)\n",
    "    root_3 = TreeNode(3)\n",
    "    node_4 = TreeNode(4)\n",
    "    root_3.left = node_1\n",
    "    root_3.right = node_4\n",
    "    node_1.right = node_2\n",
    "\n",
    "    print(kthSmallest(root_3, 1))\n",
    "    print(kthSmallest(root_3, 2))\n",
    "    print(kthSmallest(root_3, 3))\n",
    "    print(kthSmallest(root_3, 4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
